package cn.kgc.service.impl;

import cn.kgc.client.WmsWareSkuFeignClient;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.vo.Result;
import cn.kgc.constant.PmsSpuDefaultImage;
import cn.kgc.constant.PmsSpuStatus;
import cn.kgc.dto.*;
import cn.kgc.dto.add.*;
import cn.kgc.entity.*;
import cn.kgc.client.SmsSpuFeignClient;
import cn.kgc.mapper.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.service.PmsSpuInfoService;
import io.netty.handler.codec.http2.Http2SecurityUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * spu信息(PmsSpuInfo)表服务实现类
 *
 * @author makejava
 * @since 2022-12-05 09:38:36
 */
@Service("pmsSpuInfoService")
@Slf4j
public class PmsSpuInfoServiceImpl extends ServiceImpl<PmsSpuInfoMapper, PmsSpuInfo> implements PmsSpuInfoService {
    @Resource
    private PmsSpuInfoMapper pmsSpuInfoMapper;
    @Resource
    private PmsSpuInfoDescMapper pmsSpuInfoDescMapper;
    @Resource
    private PmsSpuImagesMapper pmsSpuImagesMapper;
    @Resource
    private PmsProductAttrValueMapper pmsProductAttrValueMapper;
    @Resource
    private PmsAttrMapper pmsAttrMapper;
    @Resource
    private PmsSkuInfoMapper pmsSkuInfoMapper;
    @Resource
    private PmsSkuImagesMapper pmsSkuImagesMapper;
    @Resource
    private PmsSkuSaleAttrValueMapper pmsSkuSaleAttrValueMapper;

    @Resource
    private SmsSpuFeignClient smsSpuFeignClient;
    @Resource
    private PmsBrandMapper pmsBrandMapper;
    @Resource
    private WmsWareSkuFeignClient wmsWareSkuFeignClient;
    @Resource
    private PmsCategoryMapper pmsCategoryMapper;

    @Resource
    private SkuEsModelElasticsearchRepository skuEsModelElasticsearchRepository;

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;
    @Resource
    private PmsAttrGroupMapper pmsAttrGroupMapper;
    @Resource
    private PmsAttrAttrgroupRelationMapper pmsAttrAttrgroupRelationMapper;

    @Override
    public SpuItemVO selectById(Long skuId) {
        SpuItemVO spuItemVO = new SpuItemVO();
        // 商品的基本信息
        CompletableFuture<PmsSkuInfo> pmsSkuInfoCompletableFuture = CompletableFuture.supplyAsync(() -> {
            PmsSkuInfo skuInfo = pmsSkuInfoMapper.selectById(skuId);
            long brandId = skuInfo.getBrandId();
            PmsBrand pmsBrand = pmsBrandMapper.selectById(brandId);
            skuInfo.setBrandName(pmsBrand.getName());
            long categoryId = skuInfo.getCatalogId();
            PmsCategory pmsCategory = pmsCategoryMapper.selectById(categoryId);
            skuInfo.setCatalogName(pmsCategory.getName());
            long spuId = skuInfo.getSpuId();
            PmsSpuInfo pmsSpuInfo = pmsSpuInfoMapper.selectById(spuId);
            skuInfo.setSpuName(pmsSpuInfo.getSpuName());
            spuItemVO.setPmsSkuInfo(skuInfo);
            return skuInfo;
        }, threadPoolExecutor);
        //商品的图片信息
        CompletableFuture<Void> pmsSkuImagesCompletableFuture = CompletableFuture.runAsync(() -> {
            List<PmsSkuImages> pmsSkuImages = pmsSkuImagesMapper.selectList(
                    new LambdaQueryWrapper<PmsSkuImages>().eq(PmsSkuImages::getSkuId, skuId));
            spuItemVO.setImagesList(pmsSkuImages);
        }, threadPoolExecutor);
        //商品销售属性
        CompletableFuture<Void> pmsSkuSaleAttrValueCompletableFuture = CompletableFuture.runAsync(() -> {
            List<PmsSkuSaleAttrValue> pmsSkuSaleAttrValues = pmsSkuSaleAttrValueMapper.selectList(
                    new LambdaQueryWrapper<PmsSkuSaleAttrValue>().eq(PmsSkuSaleAttrValue::getSkuId, skuId));
            List<Attr> attrList = pmsSkuSaleAttrValues.stream().map(pmsSkuSaleAttrValue -> {
                Attr attr = new Attr();
                BeanUtils.copyProperties(pmsSkuSaleAttrValue, attr);
                return attr;
            }).collect(Collectors.toList());

            spuItemVO.setPmsSkuItemSaleAttrVoList(attrList);
        }, threadPoolExecutor);
        //获取SPU的介绍信息
        CompletableFuture<Void> pmsSpuInfoDescCompletableFuture = pmsSkuInfoCompletableFuture.thenAcceptAsync(pmsSkuInfo -> {
            Long spuId = pmsSkuInfo.getSpuId();
            PmsSpuInfoDesc pmsSpuInfoDesc = pmsSpuInfoDescMapper.selectById(spuId);
            spuItemVO.setPmsSpuInfoDesc(pmsSpuInfoDesc);
        }, threadPoolExecutor);
        //spu属性组
        CompletableFuture<Void> pmsAttrGroupCompletableFuture =
                pmsSkuInfoCompletableFuture.thenAcceptAsync(pmsSkuInfo -> {
                    //商品基本信息对应的分类的id
                    Long catalogId = pmsSkuInfo.getCatalogId();
                    //最终商品要对应的属性组的集合
                    List<SpuItemVO.PmsSpuItemGroupAttrVo> pmsSpuItemGroupAttrVos = new ArrayList<>();
                    LambdaQueryWrapper<PmsAttrGroup> pmsAttrGroupLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    pmsAttrGroupLambdaQueryWrapper.eq(PmsAttrGroup::getCatelogId, catalogId);
                    List<PmsAttrGroup> pmsAttrGroups=pmsAttrGroupMapper.selectList(pmsAttrGroupLambdaQueryWrapper);
                    for (PmsAttrGroup pmsAttrGroup : pmsAttrGroups) {
                        SpuItemVO.PmsSpuItemGroupAttrVo pmsSpuItemGroupAttrVo = new SpuItemVO.PmsSpuItemGroupAttrVo();
                        //获得属性组的名字
                        String attrGroupName=pmsAttrGroup.getAttrGroupName();
                        pmsSpuItemGroupAttrVo.setGroupName(attrGroupName);
                        //获得商品对应的基本属性
                        //1 通过属性组的id，获得属性组和属性关联关系的集合
                        Long attrGroupId=pmsAttrGroup.getId();
                        LambdaQueryWrapper<PmsAttrAttrgroupRelation> pmsAttrAttrgroupRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
                        pmsAttrAttrgroupRelationLambdaQueryWrapper.eq(PmsAttrAttrgroupRelation::getAttrGroupId, attrGroupId);
                        List<PmsAttrAttrgroupRelation>  pmsAttrAttrgroupRelations=
                                pmsAttrAttrgroupRelationMapper.selectList(pmsAttrAttrgroupRelationLambdaQueryWrapper);
                        // 属性组对应的基本属性的集合
                        List<Attr> baseAttrList=new ArrayList<>();
                        //2 通过属性组和属性关联关系的集合，获得属性的id的集合，获得属性所对应的属性的信息
                        for (PmsAttrAttrgroupRelation pmsAttrAttrgroupRelation : pmsAttrAttrgroupRelations) {
                            Long attrId=pmsAttrAttrgroupRelation.getAttrId();
                            //3 通过属性的id和商品的id去商品属性表中获得属性的信息
                            LambdaQueryWrapper<PmsProductAttrValue> pmsProductAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            pmsProductAttrValueLambdaQueryWrapper.eq(PmsProductAttrValue::getSpuId, pmsSkuInfo.getSpuId());
                            pmsProductAttrValueLambdaQueryWrapper.eq(PmsProductAttrValue::getAttrId, attrId);
                            PmsProductAttrValue pmsProductAttrValue =
                                    pmsProductAttrValueMapper.selectOne(pmsProductAttrValueLambdaQueryWrapper);
                            Attr attr = new Attr();
                            BeanUtils.copyProperties(pmsProductAttrValue, attr);
                            baseAttrList.add(attr);
                        }
                        pmsSpuItemGroupAttrVo.setBaseAttrs(baseAttrList);
                        pmsSpuItemGroupAttrVos.add(pmsSpuItemGroupAttrVo);
                    }
                    spuItemVO.setPmsSpuItemGroupAttrVos(pmsSpuItemGroupAttrVos);
                }, threadPoolExecutor);
        //等待所有的异步任务都执行完毕以后，在向下执行
        CompletableFuture.allOf(pmsSpuInfoDescCompletableFuture,
                pmsAttrGroupCompletableFuture,
                pmsSkuImagesCompletableFuture,
                pmsSkuSaleAttrValueCompletableFuture).join();
        return spuItemVO;
    }

    /**
     * 实现商品的上下架功能
     * @param spuId 商品的id
     * @param status 商品要修改的的状态（上架和下架）
     * @return
     */
    private PmsSpuInfo updateSpuStatus(long spuId,short status) {
        PmsSpuInfo pmsSpuInfo = pmsSpuInfoMapper.selectById(spuId);
        if (pmsSpuInfo == null) {
            throw new HttpException(20005,HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        if(pmsSpuInfo.getPublishStatus()== status){ //修改状态和原有状态一样
            if (status == PmsSpuStatus.PUBLISH.getStatus()) {
                throw new HttpException(20006,HttpStatus.INTERNAL_SERVER_ERROR.value());
            } else {
                throw new HttpException(20007,HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        }
        pmsSpuInfo.setPublishStatus(status);
        pmsSpuInfoMapper.updateById(pmsSpuInfo);
        return pmsSpuInfo;
    }
    private void getSkuAttrValue(PmsSkuInfo pmsSkuInfo, SkuEsModel skuEsModel) {
        //销售属性信息
        LambdaQueryWrapper<PmsSkuSaleAttrValue> pmsSkuSaleAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<PmsSkuSaleAttrValue> pmsSkuSaleAttrValues = pmsSkuSaleAttrValueMapper.selectList
                (pmsSkuSaleAttrValueLambdaQueryWrapper.eq(PmsSkuSaleAttrValue::getSkuId, pmsSkuInfo.getId()));
        List<SkuEsModel.Attrs> attrsList=new ArrayList<>();
        for (PmsSkuSaleAttrValue pmsSkuSaleAttrValue : pmsSkuSaleAttrValues) {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(pmsSkuSaleAttrValue, attrs);
            attrsList.add(attrs);
        }
        skuEsModel.setAttrList(attrsList);
    }

    private List<SkuEsModel> getSkuEsModel(long spuId) {
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        LambdaQueryWrapper<PmsSkuInfo> pmsSkuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        pmsSkuInfoLambdaQueryWrapper.eq(PmsSkuInfo::getSpuId,spuId);
        List<PmsSkuInfo> pmsSkuInfoList=pmsSkuInfoMapper.selectList(pmsSkuInfoLambdaQueryWrapper);
        //每个sku对应的都是一个es中的skuEsmodel对象
        for (PmsSkuInfo pmsSkuInfo : pmsSkuInfoList) {
            SkuEsModel skuEsModel=new SkuEsModel(); //一个es中的sku对象
            skuEsModel.setSpuId(spuId);//spu的id
            skuEsModel.setSkuId(pmsSkuInfo.getId());//  sku的id
            skuEsModel.setSubTitle(pmsSkuInfo.getSkuSubtitle());//sku的标题
            skuEsModel.setSkuPrice(pmsSkuInfo.getPrice());//sku的价格
            skuEsModel.setSkuImg(pmsSkuInfo.getSkuDefaultImg());//sku的默认图片
            skuEsModel.setSaleCount(pmsSkuInfo.getSaleCount());//sku的销量
            skuEsModel.setBrandId(pmsSkuInfo.getBrandId());//sku的品牌id
            skuEsModel.setCategoryId(pmsSkuInfo.getCatalogId());//sku的分类id
            PmsBrand pmsBrand = pmsBrandMapper.selectById(pmsSkuInfo.getBrandId());
            if (pmsBrand != null) {
                //品牌名字
                skuEsModel.setBrandName(pmsBrand.getName());
                //品牌图片
                skuEsModel.setBrandImg(pmsBrand.getLogo());
            }
            //属性信息
            getSkuAttrValue(pmsSkuInfo, skuEsModel);
            PmsCategory pmsCategory=pmsCategoryMapper.selectById(pmsSkuInfo.getCatalogId());
            if (pmsCategory!=null){
                //分类名字
                skuEsModel.setCategoryName(pmsCategory.getName());
            }
            //是否还有库存
            boolean hasStock=wmsWareSkuFeignClient.hasStock(pmsSkuInfo.getId()).getData();
            skuEsModel.setHasStock(hasStock);
            skuEsModels.add(skuEsModel);
        }
        return skuEsModels;
    }



    @Transactional
    public boolean up(long spuId) {
        log.info("上架商品spuId:{}", spuId);
        //1.修改商品状态，判断商品是否已经上架，如果没有上架，再去上架
        PmsSpuInfo pmsSpuInfo = updateSpuStatus(spuId, PmsSpuStatus.PUBLISH.getStatus());
        //2 收集商品对应的sku信息
        List<SkuEsModel> skuEsModels = getSkuEsModel(spuId);
        //System.out.println(JSON.toJSONString(skuEsModels));
        //3 将sku的信息保存到es中
        for (SkuEsModel skuEsModel : skuEsModels) {
            skuEsModelElasticsearchRepository.save(skuEsModel);
        }
        return true;
    }





    @Override
    public boolean down(long spuId) {
        return false;
    }

    @GlobalTransactional
    public boolean savePmsSpuInfo(SpuInfoVO spuInfoVO) {
        //新增pms_spu_info 商品的spu信息
        PmsSpuInfo pmsSpuInfo = new PmsSpuInfo();
        BeanUtils.copyProperties(spuInfoVO,pmsSpuInfo);
        pmsSpuInfoMapper.insert(pmsSpuInfo);

        //新增pms_spu_info_desc 商品的spu信息介绍
        List<String> descriptList=spuInfoVO.getDecript();
        PmsSpuInfoDesc pmsSpuInfoDesc = new PmsSpuInfoDesc();
        pmsSpuInfoDesc.setId(pmsSpuInfo.getId());
        String desc="";
        for (String s : descriptList) {
            desc +=s+";";
        }
        pmsSpuInfoDesc.setDecript(desc);
        pmsSpuInfoDescMapper.insert(pmsSpuInfoDesc);


        //pms_spu_images 商品的spu图片集
        List<String > spuImages=spuInfoVO.getImages();
        int count=0;
        for (String spuImage : spuImages) {
            PmsSpuImages pmsSpuImages = new PmsSpuImages();
            pmsSpuImages.setSpuId(pmsSpuInfo.getId());
            pmsSpuImages.setImgName(spuImage);
            pmsSpuImages.setImgUrl(spuImage);
            if (count==0){ //将集合的第一张图片当作默认图片
                pmsSpuImages.setDefaultImg(PmsSpuDefaultImage.DEFAULT_IMAGE.getDefaultImage()); //是否是默认图片
            }
            pmsSpuImagesMapper.insert(pmsSpuImages);
            count++;
        }

        //pms_product_attr_value`商品基本属性
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        for (BaseAttrs baseAttr : baseAttrs) {
            PmsProductAttrValue pmsProductAttrValue = new PmsProductAttrValue();
            pmsProductAttrValue.setAttrId(baseAttr.getAttrId());// 基础属性的id
            String attrName=pmsAttrMapper.selectById(baseAttr.getAttrId()).getAttrName(); //基础属性的名字
            pmsProductAttrValue.setAttrName(attrName);
            pmsProductAttrValue.setAttrValue(baseAttr.getAttrValues());//基本属性的值
            pmsProductAttrValue.setAttrSort(baseAttr.getShowDesc());//基本属性的排序
            pmsProductAttrValue.setSpuId(pmsSpuInfo.getId());
            pmsProductAttrValue.setQuickShow(baseAttr.getQuickShow()); //是否快速展示
            pmsProductAttrValueMapper.insert(pmsProductAttrValue);
        }
        // pms_sku_images`商品的图片信息
        List<Skus> skusList=spuInfoVO.getSkus();
        PmsSkuInfo pmsSkuInfo = new PmsSkuInfo();
        count=0;
        // 商品sku图片
        PmsSkuImages pmsSkuImages = new PmsSkuImages();
        // 商品的销售属性
        PmsSkuSaleAttrValue pmsSkuSaleAttrValue = new PmsSkuSaleAttrValue();
        //sku会员价格
        List<SmsMemberPriceAddDTO> smsMemberPriceAddDTOS = new ArrayList<>();
        //sku打折信息
        List<SmsSkuLadderAddDTO> smsSkuLadderAddDTOList = new ArrayList<>();
        //sku满减信息
        List<SmsSkuFullReductionAddDTO> smsSkuFullReductionAddDTOList = new ArrayList<>();
        for (Skus skus : skusList) {
          pmsSkuInfo.setBrandId(pmsSpuInfo.getBrandId());
          pmsSkuInfo.setCatalogId(pmsSpuInfo.getCatalogId());
          pmsSkuInfo.setSpuId(pmsSpuInfo.getId());
          pmsSkuInfo.setSkuName(skus.getSkuName());
          pmsSkuInfo.setPrice(skus.getPrice());
          pmsSkuInfo.setSaleCount(0L);
          pmsSkuInfo.setSkuDefaultImg(skus.getImages().get(0));
          pmsSkuInfo.setSkuDesc(skus.getDescar().toString());
          pmsSkuInfo.setSkuSubtitle(skus.getSkuSubtitle());
          pmsSkuInfo.setSkuTitle(skus.getSkuTitle());
          pmsSkuInfoMapper.insert(pmsSkuInfo);

          //pms_sku_images`商品的图片信息
          List<String> images = skus.getImages();
          int index=0;
            for (String image : images) {
                if (index==0){
                    pmsSkuImages.setDefaultImg(1);
                }
                pmsSkuImages.setImgSort(0);
                pmsSkuImages.setImgUrl(image);
                pmsSkuImages.setSkuId(pmsSkuInfo.getId());
                pmsSkuImagesMapper.insert(pmsSkuImages);
                index++;
            }
            //pms_sku_sale_attr_value`商品的销售属性
            List<Attr> saleAttrsList=skus.getAttr();
            for (Attr attr : saleAttrsList) {
                pmsSkuSaleAttrValue.setAttrId(attr.getAttrId());
                pmsSkuSaleAttrValue.setAttrName(attr.getAttrName());
                pmsSkuSaleAttrValue.setAttrSort(0);
                pmsSkuSaleAttrValue.setAttrValue(attr.getAttrValue());
                pmsSkuSaleAttrValue.setSkuId(pmsSkuInfo.getId());
                pmsSkuSaleAttrValueMapper.insert(pmsSkuSaleAttrValue);
            }
            count++;

            //每个sku会员价格
            List<MemberPrice> memberPriceList=skus.getMemberPrice();
            for (MemberPrice memberPrice : memberPriceList) {
                SmsMemberPriceAddDTO smsMemberPriceAddDTO = new SmsMemberPriceAddDTO();
                smsMemberPriceAddDTO.setAddOther((short)0);
                smsMemberPriceAddDTO.setMemberLevelId(memberPrice.getId());
                smsMemberPriceAddDTO.setMemberLevelName(memberPrice.getName());
                smsMemberPriceAddDTO.setMemberPrice(memberPrice.getPrice());
                smsMemberPriceAddDTO.setSkuId(pmsSkuInfo.getId());
                smsMemberPriceAddDTOS.add(smsMemberPriceAddDTO);
            }

            //每个sku打折信息
            SmsSkuLadderAddDTO smsSkuLadderAddDTO = new SmsSkuLadderAddDTO();
            smsSkuLadderAddDTO.setAddOther((short)0);
            smsSkuLadderAddDTO.setFullCount(skus.getFullCount());
            smsSkuLadderAddDTO.setPrice(skus.getPrice());
            smsSkuLadderAddDTO.setSkuId(pmsSkuInfo.getId());
            smsSkuLadderAddDTO.setDiscount(skus.getDiscount());
            //保存打折的信息到集合中
            smsSkuLadderAddDTOList.add(smsSkuLadderAddDTO);

            //商品的满减
            SmsSkuFullReductionAddDTO smsSkuFullReductionAddDTO = new SmsSkuFullReductionAddDTO();
            smsSkuFullReductionAddDTO.setAddOther((short)0);
            smsSkuFullReductionAddDTO.setSkuId(pmsSkuInfo.getId());
            smsSkuFullReductionAddDTO.setFullPrice(skus.getFullPrice());
            smsSkuFullReductionAddDTO.setReducePrice(skus.getReducePrice());
            smsSkuFullReductionAddDTOList.add(smsSkuFullReductionAddDTO);
        }
        //封装参数
        SmsSpuAddDTO smsSpuAddDTO=new SmsSpuAddDTO();
        SmsSpuBoundsAddDTO smsSpuBoundsAddDTO=new SmsSpuBoundsAddDTO();
        //前端传入得积分信息
        Bounds bounds = spuInfoVO.getBounds();
        smsSpuBoundsAddDTO.setBuyBounds(bounds.getBuyBounds());
        smsSpuBoundsAddDTO.setGrowBounds(bounds.getGrowBounds());
        smsSpuBoundsAddDTO.setSpuId(pmsSpuInfo.getId());
        //商品的成长积分购买积分
        smsSpuAddDTO.setSmsSpuBoundsAddDTO(smsSpuBoundsAddDTO);

        //商品的会员价格
        smsSpuAddDTO.setSmsMemberPriceAddDTOList(smsMemberPriceAddDTOS);

        //商品的折扣
        smsSpuAddDTO.setSmsSkuLadderAddDTOList(smsSkuLadderAddDTOList);

        //商品的满减
        smsSpuAddDTO.setSmsSkuFullReductionAddDTOList(smsSkuFullReductionAddDTOList);
        //调用远程服务
        Result result=smsSpuFeignClient.saveSmsSpu(smsSpuAddDTO);
        if (result.getCode()== HttpStatus.INTERNAL_SERVER_ERROR.value()){
            throw new HttpException(20004,500);
        }
        return true;
    }
}
